package com.test.springboottest.controller;

import com.test.springboottest.domain.User;
import com.test.springboottest.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author liqingbo
 */
@Controller
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("login")
    public String login(String uname, String upwd, Model model, HttpSession session) {
        User user;
        user = userService.getLoginUser(uname, upwd);
        if (user != null) {
            session.setAttribute("user", uname);
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "用户名或密码输入错误。");
            return "login";
        }
    }

    /**
     * 获取所有的用户列表
     *
     * @param model
     * @return
     */
    @GetMapping("/users")
    public String getUsers(Model model) {
        //调用业务逻辑层获取所有的用户列表
        List<User> userList = userService.getUserList();
        model.addAttribute("userList", userList);
        return "userList";
    }

    /**
     * 打开修改页面，查询当前要修改的用户（uid），在页面进行回显
     *
     * @param uid
     * @param model
     * @return
     */
    @GetMapping("/user/{uid}")
    public String toModifyUser(@PathVariable("uid") int uid, Model model) {
        //调用业务逻辑层根据uid查询用户
        User user = userService.getUserByUid(uid);
        //保存到model对象中
        model.addAttribute(user);
        return "modifyUser";
    }

    @PutMapping("/user")
    public String modifyUser(User user) {
        //调用业务逻辑层修改用户
        userService.modifyUser(user);
        return "redirect:/users";
    }

    @DeleteMapping("/user/{uid}")
    public String deleteUser(@PathVariable("uid") Integer uid) {
        //调用业务逻辑层删除用户
        userService.deleteUserByUid(uid);
        return "redirect:/users";
    }

    @GetMapping("/user")
    public String toAddUser() {
        return "adduser";
    }

    @PostMapping("/user")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:users";
    }

}
